package com.shelpe.services.lexicon.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.shelpe.services.lexicon.entity.KeywordMetric;

import lombok.Getter;
import lombok.Setter;


@Service
public class MetricThreadCache {

	private final static String PREFIX_DEFAULT = "single";
	private ThreadLocal<Map<String, KeywordMetrics>> cache = new ThreadLocal<Map<String, KeywordMetrics>>();
	
	public void put(String word, String prefix, KeywordMetric metric){
		List<KeywordMetric> metrics = new ArrayList<KeywordMetric>();
		this.put(word, prefix, metrics);
	}
	
	public void put(String word, String prefix, List<KeywordMetric> metrics){
		if(StringUtils.isBlank(prefix)){
			prefix = PREFIX_DEFAULT;
		}
		
		String key = prefix + "_" + word;
		if(cache.get() == null){
			cache.set(new HashMap<String, KeywordMetrics>());
		}
		
		KeywordMetrics entry = new KeywordMetrics();
		entry.setMetrics(metrics);
		cache.get().put(key, entry);
	}
	
	public List<KeywordMetric> get(String word, String prefix){
		if(StringUtils.isBlank(prefix)){
			prefix = PREFIX_DEFAULT;
		}
		List<KeywordMetric> metrics = null;
		String key = prefix + "_" + word;
		
		if(cache.get() != null){
			KeywordMetrics value = cache.get().get(key);
			if(value != null){
				metrics = value.getMetrics();
			}
		}
		
		return metrics;
	}
	
	@Setter
	@Getter
	private static class KeywordMetrics{
		private List<KeywordMetric> metrics;
	}

}
